﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;

namespace DA.AnimGraph.Editor {

    internal class LauncherPane : TrinityPaneBase {

        class AGAItem : ISearchListItem {
            public string path;
            public string name;

            public AGAItem(AGAFileTool.File file) {
                path = file.path;
                name = Path.GetFileNameWithoutExtension(path);
            }
            public string GetName() => name;
            public string GetPath() => path;
            public (string, Action<ISearchListItem>)[] GetActions() {
                return new (string, Action<ISearchListItem>)[] {
                    ("打开", OpenFile),
                    ("导出", Export),
                    ("定位", Ping)
                };
            }
            static void OpenFile(ISearchListItem item) {
                AnimGraphEditorWindow.OpenWindow(item.GetPath());
            }
            static void Export(ISearchListItem item) {
                int skipNum = 0;
                int completeNum = 0;
                int failNum = 0;
                Tool_Export.SaveEditingFile();
                Tool_Export.Export(item.GetPath(), false, ref completeNum, ref skipNum, ref failNum);
            }
            static void Ping(ISearchListItem item) {
                var asset = AssetDatabase.LoadAssetAtPath<AnimGraphArchiveAsset>(item.GetPath());
                EditorGUIUtility.PingObject(asset);
            }
        }

        private SearchList searchList;

        public LauncherPane(NonContextPaneBase parent) : base(parent) {
            searchList = new SearchList();
        }

        protected override void OnDrawUI() {
            Add(leftContainer);
            Add(middleContainer);
            Add(rightContainer);

            DrawSearchList();
            middleContainer.Add(searchList);
        }
        protected override void OnClearUI() {
            Clear();
        }
        void DrawSearchList() {
            var fileList = AGEGlobal.GetInstance().fileTool.agaList;
            List<ISearchListItem> itemsSource = fileList.Select(x => new AGAItem(x) as ISearchListItem).ToList();
            searchList.itemsSource = itemsSource;
        }

        protected override void OnUpdateUI() {
            if (AGAFileTool.agaListDirty) {
                DrawSearchList();
            }
        }

    }
}
